package com.qianfeng.user.service;


import java.util.List;

import com.qianfeng.user.bean.Address;
import com.qianfeng.user.mapper.AddressMapper;
import com.qianfeng.utils.DBUtils;

public class AddressService {
	
	
	/*
	 * 根据用户id查询用户的收货地址
	 * @param user_id
	 * @return
	 */
	public List<Address> getAddressesByUserId(long user_id){
		AddressMapper addressMapper=DBUtils.getMapper(AddressMapper.class);
		List<Address>list=addressMapper.getAddressesByUserId(user_id);
		DBUtils.release();
		return list;
		
	}
	/**
	 * 根据地址id和用户id删除地址
	 * @param address
	 * @return
	 */
	public boolean deleteById(Address address) {
		AddressMapper addressMapper=DBUtils.getMapper(AddressMapper.class);
		int num = addressMapper.deleteByAddressIdAndUserId(address);
		DBUtils.release();
		return num > 0;
	}
	
	/**
	  * 保存用户的收货地址,如果是第一次添加, 那么, 设为默认收货地址
	 * @param address
	 * @return
	 */
	public boolean saveAddress(Address address) {
		AddressMapper addressMapper=DBUtils.getMapper(AddressMapper.class);
		//每个新天加的收货地址都需要一个创建时间用来排序
		address.setCreate_time(System.currentTimeMillis());
		//判断之前是不是已经添加过收货地址了, 如果不是, 说明当前操作是第一次
		List<Address> list = addressMapper.getAddressesByUserId(address.getUser_id());
		if(list.size() == 0) {
			address.setIsdefault(1);//如果是第一次添加,当前收货地址设置为默认收货地址
		}
		int num = addressMapper.saveAddress(address);
		DBUtils.release();
		return num > 0;
		
	}
	/**
	 * 更新收货地址
	 * @param address
	 * @return
	 */
	public boolean updateAddress(Address address) {
		AddressMapper addressMapper=DBUtils.getMapper(AddressMapper.class);
		int num = addressMapper.updateByAddressIdAndUserId(address);
		DBUtils.release();
		return num > 0;
		
	}
	//设置默认收货地址
	public boolean addressChangeDefault(Address address) {
		AddressMapper addressMapper=DBUtils.getMapper(AddressMapper.class);
		int num=addressMapper.updateDefualtByUserId(address);
		if(num>0) {
		int num1=addressMapper.updateDefualtByAddressId(address);
		return num1>0;
		}
		return false;
	}
}
